<template>
  <div class="container">
    <div class="calcMain" v-show="panel == 'calc'">
      <div class="topBtn">
        <div class="flexAlign">
<!--          <span class="pageTitle">{{ commitModel.name }}</span>-->
          <span class="pageTitle">{{ commitModel.name + '评估模型计算' }}<span class="huiTitle">{{'(任务版本V'+Number(commitModel.version).toFixed(1)+')'}}</span></span>

        </div>

        <div class="flexAlign">
          <el-button class="flexAlign" v-if="historyShow" @click="backQuery" type="primary" size="small" >
            返回最新版本
          </el-button>
          <div class="line"></div>
          <el-button class="flexAlign" type="primary" size="mini" @click="calc" :disabled="historyShow">
            <img :src="require('@/assets/images/ji1.png')" alt="" srcset="" />
            计算
          </el-button>
          <el-button :disabled="jsRes" class="flexAlign" type="primary" size="mini" @click="baocun">
            <img :src="require('@/assets/images/baocun.png')" alt="" srcset="" />
            保存结果
          </el-button>
          <el-button class="flexAlign" size="mini" @click="resultHistory">
            <img :src="require('@/assets/images/bao1.png')" alt="" srcset="" />
            保存结果记录
          </el-button>
<!--          <el-button class="flexAlign" size="mini" @click="importByCao">-->
<!--            <img :src="require('@/assets/images/cao111.png')" alt="" srcset="" />-->
<!--            草稿箱导入-->
<!--          </el-button>-->
        </div>
      </div>
      <div class="bottomMain">
        <div class="title1 flexAlign">
          <img :src="require('@/assets/images/shu2.png')" alt="" srcset="" />
          数据预处理
        </div>
        <div class="tableContainer">
          <div class="topBtn" style="border: none; padding: 0">
            <div class="flexAlign">
              <el-input
                class="searchInput"
                size="mini"
                placeholder="搜索指标名称"
                prefix-icon="el-icon-search"
                v-model="input4"
              >
              </el-input>
              <el-button class="flexAlign" type="primary" size="mini" @click="searchP">
                <img :src="require('@/assets/images/cha3.png')" alt="" srcset="" />
                查询
              </el-button>
              <el-button
                class="flexAlign"
                type="primary"
                size="mini"
                :disabled="historyShow"
                @click="showlinkDialog"
              >
                <img
                  :src="require('@/assets/images/dong3.png')"
                  alt=""
                  srcset=""
                />
                动态接引
              </el-button>
              <el-upload
                class="uploadDemo"
                action=""
                ref='upload'
                @clearFiles="clearFiles"
                :http-request="uploadFile"
                :multiple="false"
                :show-file-list="false"
                :limit="1"
                :file-list="fileList"
              >
                <el-button class="flexAlign" type="primary" size="mini" :disabled="historyShow">
                  <img :src="require('@/assets/images/dao1.png')" />
                  打分表导入
                </el-button>
              </el-upload>
            </div>
            <div class="flexAlign">
              <el-button
                class="flexAlign"
                size="mini"
                :disabled="historyShow"
                @click="
                  () => {
                    downTable('1');
                  }
                "
              >
                <img :src="require('@/assets/images/xiaz.png')" alt="" srcset="" />
                试验员打分表下载
              </el-button>
              <el-button
                class="flexAlign"
                size="mini"
                :disabled="historyShow"
                @click="downTable('2')"
              >
                <img :src="require('@/assets/images/xiaz.png')" alt="" srcset="" />
                专家打分表下载
              </el-button>
            </div>
          </div>
          <el-form class="base-form" ref="demoList" :model="demoList" :rules="rulesOptions" auto-complete="on">
          <el-table class="myTabel" :data="demoList.pretreatmentList" border stripe size="mini"  height="400" :header-cell-style="{ textAlign: 'center',  }"
                    :cell-style="{'text-align':'center'}">
            <el-table-column type="index" align="center" label="序号" width="50">
            </el-table-column>
            <el-table-column prop="name" label="指标名称"> </el-table-column>
            <el-table-column prop="normalizationAlgSet" align="center" label="系统数据录入" width="130">
              <template slot-scope="scope">
                <el-form-item style="margin-bottom: 12px" :prop="'pretreatmentList.'+scope.$index+'.normalizationAlgSet'"
                              :rules="getValidationRules(scope.row.dataPreprocessingAlg)" class="all">
                  <el-input
                    v-if="commitModel.status=='0' || commitModel.status=='1'"
                    size="mini"
                    :disabled="historyShow"
                    style="margin-top: 9px"
                    class="tableLineInput"
                    placeholder="请输入"
                    @change="
                    (val) => {
                      tableInputFun(val, scope.row.id);
                    }
                  "
                    v-model="scope.row.normalizationAlgSet"
                  >
                  </el-input>
                  <span v-else>{{scope.row.normalizationAlgSet}}</span>
                </el-form-item>

              </template>
            </el-table-column>
            <el-table-column prop="sourceType" align="center" label="数据来源" >
              <template slot-scope="scope">
                <el-select
                  v-if="commitModel.status=='0' || commitModel.status=='1'"
                  v-model="scope.row.sourceType"
                  :disabled="historyShow"
                  placeholder="请选择"
                  size="mini"
                  @change="
                    (val) => {
                      tableSelectFun(val, scope.row.id);
                    }
                  "
                >
                  <el-option
                    v-for="item in cities"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                    <span style="float: left">{{ item.dictLabel }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ item.dictValue }}
                    </span>
                  </el-option>
                </el-select>
                <span v-else>{{scope.row.sourceType}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="unit" align="center" label="量纲"> </el-table-column>
            <el-table-column prop="originalValue"  align="center" label="导入的数据值" width="150">
              <template slot-scope="scope">
                <el-form-item style="margin-bottom: 12px" :prop="'pretreatmentList.'+scope.$index+'.originalValue'" :rules="getValidationRules(scope.row.dataPreprocessingAlg)" class="all">
                  <el-input
                    size="mini"
                    :disabled="historyShow"
                    style="width: 130px;"
                    class="tableLineInput"
                    placeholder="请输入"
                    @input="queryPre(demoList.pretreatmentList,scope.$index,scope.row)"
                    v-model="scope.row.originalValue"
                  >
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="dataPreprocessingAlg" label="处理方法" width="650">
              <template slot-scope="scope">
                <el-steps style="font-size: 12px" align-center v-if="scope.row.dataPreprocessingAlg">
                  <el-step
                    v-for="(item, index) in scope.row.dataPreprocessingAlg.split(',')"
                    :description="item"
                  ></el-step>
                </el-steps>
              </template>
            </el-table-column>
            <el-table-column prop="name" align="center" label="数据预处理" width="100">
              <template slot-scope="scope">
                <el-button
                  :disabled="commitModel.status=='2'||  historyShow"
                  @click.native.prevent="deleteRow(scope.row,scope.$index)"
                  type="text"
                  size="small"
                >
                  <img
                    :src="require('@/assets/images/xiug.png')"
                    alt=""
                    srcset=""
                  />
                  设置
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          </el-form>
          <el-pagination
            background
            layout="total, prev, pager, next"
            :total="pTotal"
            :current-page="pCurrPage"
            @current-change="changePPage"
            style="text-align: right"
          >
          </el-pagination>
        </div>
        <div class="title2 flexAlign">
          <img
            :src="require('@/assets/images/jisuan.png')"
            alt=""
            srcset=""
          />计算结果
        </div>
        <g6-container class="graph" ref="graphBase" :treedata="g6Tree"  @imgBase64="getBase64"></g6-container>
        <div class="bottomBtn">
          <el-button :disabled="historyShow" class="flexAlign" type="primary" size="mini" @click="zancun">
            <img :src="require('@/assets/images/zancun.png')" alt="" srcset="" />
            暂存
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog title="设置数据处理方法" :visible.sync="methodsDialog" width="70%">
      <div style="margin-bottom: 20px;display: flex;align-items: center">
        <div style="font-size: 16px;line-height: 25px">指标名称 </div><div class="lineBlue"></div>
        <el-tag
          :key="tag"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="tagClose(tag)"
        >
           {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="mini"
          style="width: 100px"
        >
        </el-input>

        <el-button v-else class="button-new-tag" size="mini" @click="showInput">
          + New Step
        </el-button>
      </div>
      <el-table :data="chuliMethods" border stripe size="mini" @row-click="chuliClick">
        <el-table-column label="选择" width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.row.key" v-model="inputValue">
              {{ "" }}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" align="center" label="序号" width="60">
        </el-table-column>
        <el-table-column prop="key" label="编号"> </el-table-column>
        <el-table-column prop="label" label="模块描述"> </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="methodsDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="commitStep" :disabled="dynamicTags.length == 0"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择时间段引接" :visible.sync="linkDialog" width="40%">
      <el-form
        :inline="true"
        size="mini"
        class="demo-form-inline"
        style="display: flex; justify-content: center"
      >
        <el-form-item label="选择开始时间">
          <el-date-picker
            v-model="linkForm"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-upload
            class="uploadDemo"
            action=""
            ref='uploadJSON'
            @clearFiles="clearFilesJSON"
            :http-request="uploadFileJSON"
            :multiple="false"
            :show-file-list="false"
            :limit="1"
            :file-list="fileList"
          >
            <el-button class="flexAlign" type="primary" size="mini">
              <img :src="require('@/assets/images/dao1.png')" />
              数据导入
            </el-button>
          </el-upload>
        </el-form-item>

      </el-form>

<!--      <span slot="footer" class="dialog-footer">-->
<!--        <el-button size="mini" @click="linkDialog = false">取 消</el-button>-->
<!--        <el-button size="mini"  type="primary" @click="link">-->
<!--          确 定-->
<!--        </el-button>-->
<!--      </span>-->
    </el-dialog>
    <el-dialog title="保存结果弹框" :visible.sync="baocunDialog" width="20%" class="baocunDia" >
      <div slot="title" class="header-title">
        <span  class="title-name">{{ '任务版本V'+(Number(commitModel.version)).toFixed(1) }}</span>
      </div>
      <el-input type="textarea" placeholder="请输入其他描述" v-model="formbaocun"></el-input>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="baocunDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="linkbaocun">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-drawer title="保存记录" :visible.sync="drawer" :direction="direction" :size="350">
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in activities"
          :key="index"
          :icon="activity.icon"
          :type="activity.type"
          :hide-timestamp="true"
          :color="activity.color"
          :size="activity.size"
        >
          <img
            class="timeItem"
            slot="dot"
            :src="require('@/assets/images/ff.png')"
            alt=""
            @click="hxTable(activity)"
          />
          <div class="hisInfoItem">
            <div style="cursor: pointer" @click="hxTable(activity)">{{ activity.name }}</div>
            <div>{{ activity.createTime }}</div>
            <div>{{ activity.createBy }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>
    <!-- 模型弹窗 -->
    <el-dialog :title="importDialogTitle" :visible.sync="importDialog" width="60%">
      <el-form
        :inline="true"
        size="mini"
        :model="formInline"
        class="demo-form-inline"
        style="display: flex; justify-content: space-between"
      >
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="formInline.createTime"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="formInline.type" placeholder="类型" clearable>
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模型名称">
          <el-input
            v-model="formInline.modelName"
            placeholder="模型名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">
            <img :src="require('@/assets/images/cha3.png')" alt="" srcset="" />
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="modelList"
        border
        stripe
        size="mini"
        @row-click="rowClick"
        show-overflow-tooltip
        highlight-current-row
      >
        <el-table-column label="选择" width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.row.id" v-model="currModelId">
              {{ "" }}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" align="center" label="序号" width="60">
        </el-table-column>
        <el-table-column prop="name" label="评估模型名称"> </el-table-column>
        <el-table-column prop="type" align="center" label="模型类型"> </el-table-column>
        <el-table-column prop="updateTime" align="center" label="暂存时间" width="150">
        </el-table-column>
        <el-table-column prop="createBy" label="创建人员"> </el-table-column>
        <el-table-column prop="polymerizationAlg" label="算法类型"> </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="modelTotle"
        :current-page="modelCurrPage"
        @current-change="changeModelPage"
        style="text-align: right"
      >
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="importDialog = false">取 消</el-button>
        <el-button
          size="mini"
          :disabled="!currModelId"
          type="primary"
          @click="commitImport"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getModelList,
  importModel,
  getPretreatmentList,
  modelCalc,
  computeValue,
  getTreeData,
  selectTreeByCode,
  exportTabel,
  exportXls,
  importTabel,
  importJsonData,
  getDictList,
  getAlgsList,
  getHistoryList,
  tempEdit,
  tempEditzqz,
  saveResult,
  getTaskModelNodeList,
  getHisTaskModelNodeList
} from "@/api/calc";

import G6Container from "@/components/G6Container/index";
const PING = "评估模型";
const CAO = "草稿箱模板";
const PINGTITLE = "选择评估模型";
const CAOTITLE = "选择草稿箱模板";

export default {
  name: "calcMain",
  components: { G6Container },
  props: {
    data: {
      type: Array,
      default: () => [],
    },

  },
  data() {
    return {
      historyShow:false,
      imgBase64:'',
      rulesOptions: {
        YCL_FFZSSF:  [{ name: "YCL_FFZSSF", description: "只能输入非负整数", pattern: /^[0-9,，.]+$/, message: "输入数字和逗号" }],
        YCL_FFSSSF: [{ name: "YCL_FFSSSF", description: "只能输入非负实数", pattern: /^[0-9,，.]+$/, message: "输入数字和逗号" }],
        YCL_ZZSSF: [{ name: "YCL_ZZSSF", description: "只能输入正整数", pattern: /^[0-9,，.]+$/, message: "输入数字和逗号" }],
        YCL_ZSSSF: [{ name: "YCL_ZSSSF", description: "只能输入正实数", pattern: /^[0-9,，.]+$/, message: "输入数字和逗号" }],
        YCL_PDSFSF: [{ name: "YCL_PDSFSF", description: "只能输入是或否", pattern: /^(是|否)$/, message: "输入是或否" }],
        YCL_PDSiDJSF: [{ name: "YCL_PDSiDJSF", description: "只能输入高或中或低或极低", pattern: /^(高|中|低|极低)$/, message: "高或中或低或极低" }],
        YCL_PDSDJSF: [{ name: "YCL_PDSDJSF", description: "只能输入高或中或低", pattern: /^(高|中|低)$/, message: "输入高或中或低" }],
      },


      jsRes:true,
      formbaocun:"",
      g6Tree:{

      },
      // g6Tree: {
      //   id: "1",
      //   num: "1.000",
      //   label: "WL系统能力",
      //   size: [120, 50],
      //   children: [
      //     {
      //       id: "2",
      //       num: "0.250",
      //       label: "WL系统能力",
      //       size: [120, 50],
      //       children: [
      //         { id: "5", num: "0.250", label: "WL系统能力", size: [40, 140] },
      //         { id: "6", num: "0.250", label: "WL系统能力", size: [40, 140] },
      //         { id: "7", num: "0.251", label: "WL系统能力", size: [40, 140] },
      //       ],
      //     },
      //     {
      //       id: "3",
      //       num: "0.250",
      //       label: "WL系统系统能系统能系统能系统能系统能系统能能力",
      //       size: [120, 50],
      //       children: [
      //         { id: "8", num: "0.250", label: "WL系统能力", size: [40, 140] },
      //         { id: "9", num: "0.250", label: "WL系统WL系统系WL系统系WL系统系WL系统系能力", size: [40, 140] },
      //         { id: "10", num: "0.250", label: "WL系统WL系统系WL系统系能力", size: [40, 140] },
      //       ],
      //     },
      //     {
      //       id: "4",
      //       num: "0.250",
      //       label: "WL系统WL系统系WL系统系能力",
      //       size: [120, 50],
      //       children: [
      //         { id: "11", num: "0.250", label: "WL系统能力", size: [40, 140] },
      //         { id: "12", num: "0.250", label: "WL系WL系统系WL系统系WL系统系WL系统系WL系统系统能力", size: [40, 140] },
      //         { id: "13", num: "0.250", label: "WL系统能力", size: [40, 140] },
      //       ],
      //     },
      //   ],
      // },
      formLabelAlign: {
        name: "",
        region: "",
        type: "",
        desc: "",
      },
      panel: "calc",
      graphG6: null,
      methodsDialog: false,
      direction: "rtl",
      activities: [
        {
          name:'',
          createTime:'',
          createBy:'',
          content: "支持使用图标",
          timestamp: "2018-04-12 20:46",
          size: "large",
          type: "primary",
          icon: "el-icon-document-copy",
        },
      ],
      drawer: false,
      linkForm: [],
      linkDialog: false,
      baocunDialog:false,
      fileList: [],
      modelType: 1,
      modelList: [],
      modelCurrPage: 1,
      modelTotle: 0,
      formInline: {
        value1: "",
        region: "",
        user: "",
      },
      importType: PING,
      importDialog: false,
      importDialogTitle: "",
      cities: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      chuliMethods: [],
      value: "",
      pCurrPage: 1,
      pTotal: 0,
      rawData: [],	// 获取表单时clone的原始数据
      demoList:{
        pretreatmentList:[],

      },
      input4: "",
      currModelId: 0, // 当前选中的模型id
      currModel: {}, // 当前选中的模型
      commitModel: {
        name:'',
        version:0,
        status:2,
      },
      taskId:'',
      emId:'',
      queryAllData:{},
    };
  },
  computed: {
    isSelectedModel: function () {
      return JSON.stringify(this.commitModel) !== "{}";
    },
  },
  created() {
    this.getDict("sys_data_source", "cities");
    // this.getDict("sys_data_methods", "chuliMethods");
    this.getAlgList();
  },
  mounted() {
  },
  methods: {
    backQuery(){
      this.historyShow = false
      this.queryAll(this.queryAllData)
      this.$refs.graphBase.refer()

    },
    queryPre(data, index, row){
      this.$set(this.demoList.pretreatmentList, index, row)
    },
    getValidationRules(rule) {
      if(rule == null){
        return
      }else{
        var selectedRule = Object.values(this.rulesOptions).find(row => row[0].name == rule.split(',')[0]);
        if(selectedRule){
          return [{
            pattern: selectedRule[0].pattern,
            message: selectedRule[0].message,
            trigger: "blur"
          }];
        }else return false

      }
    },

    queryAll(val){
      console.log(val,'新建或者选中任务传过来的值')
      this.queryAllData = val
      this.jsRes=true//计算结果按钮默认无法点,计算后才可以
      this.commitModel={
        code:'',
        name:'',
        version:0,
        status:2,
        id:'',
        emid:'',
      }
      this.commitModel.code = val.code
      this.commitModel.id = val.id
      this.commitModel.emid = val.emId
      this.commitModel.status = val.status
      this.commitModel.name=val.name
      this.commitModel.version= val.version
      this.getPretreatment()//表格数据
      //选中任务传过来的id，用id查数据赋值
    },

    // updateG6Tree(tree){
    //   this.g6Tree = tree;
    // },
    hxTable(val){

      getHisTaskModelNodeList({taskId:val.taskId,version:val.version}).then((res) => {
        if (res.code == 200) {
          this.demoList.pretreatmentList = res.data.eisEvaluationTaskModelHisDetailList;
          const data = res.data.g6
          this.formatTree(data);
          this.g6Tree = data;
          this.historyShow = true
          this.drawer = false
        }
      });
      // console.log(val,'回显的入餐')
    },

    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addTask() {
      this.panel = "add";
    },
    resultHistory() {
      getHistoryList({taskId:this.commitModel.id,}).then((res) => {
        if (res.code == 200) {
          this.activities = res.data;
        }
      });
      this.drawer = true;
    },
    tableSelectFun(val, id) {
      // let index = this.pretreatmentList.findIndex((item) => {
      //   return item.id === id;
      // });
      // let item = this.pretreatmentList[index];
      // item.originalValue = val;
      // this.$set(this.pretreatmentList, index, item);
      // console.log(this.pretreatmentList);
    },
    tableInputFun(val, id) {
      let index = this.demoList.pretreatmentList.findIndex((item) => {
        return item.id === id;
      });
      let item = this.demoList.pretreatmentList[index];
      item.normalizationAlgSet = val;
      this.$set(this.demoList.pretreatmentList, index, item);


    },
    formatTree(node) {
      if (!node) {
        return;
      }
      node.id = node.id.toString();
      node.num = node.calcValue? node.calcValue.toString(): '0';
      node.label = node.name;
      node.children = node.childList;
      if (node.level <= 3) {
        node.size = [120, 50];
      } else {
        node.size = [120, 50];
        //暂时
        // node.size = [30, 140];
      }
      if (node.children && node.children.length) {
        var i = 0;
        for (i = 0; i < node.children.length; i++) {
          this.formatTree(node.children[i]);
        }
      }
    },
    baocun() {
      this.baocunDialog = true
      this.formbaocun=''

    },
    getBase64(val){
      this.imgBase64 =val
    },
    linkbaocun(){
      this.imgBase64 =''
      this.$refs.graphBase.queryBase64()
      saveResult({
        img:this.imgBase64[1],
        id:this.commitModel.emid,
        taskId:this.commitModel.id,
        code:this.commitModel.code,
        name:this.commitModel.name,
        method:'',
        formbaocun:this.formbaocun,
        nodeList:this.demoList.pretreatmentList,
      }).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("保存成功");
          this.$emit("changePanel", {name:"task"});
          this.baocunDialog = false
        }
      });
    },
    hasChinese(str) {
      return /[\u4e00-\u9fa5]/.test(str);
    },
    zancun() {
      this.$refs.demoList.validate().then(valid => {
        if (valid) {// 表单验证通过，执行提交操作
          let nodeList = JSON.parse(JSON.stringify(this.demoList.pretreatmentList));
          nodeList.forEach(item=>{
              if(this.hasChinese(item.originalValue)){
                item.originalValue = '"' + item.originalValue + '"'
              }
            })
          tempEditzqz({
            id:this.commitModel.emid,
            taskId:this.commitModel.id,
            code:this.commitModel.code,
            name:this.commitModel.name,
            method:'',
            nodeList:nodeList,
            // taskId: this.commitModel.id,
            // code: this.commitModel.code,
            // name: this.commitModel.name,
            // nodeList: this.pretreatmentList,
          }).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("暂存成功");
            }
          });
        } else {// 表单验证不通过，不执行提交操作
        }}).catch(() => {
        this.$modal.msgWarning("请检查表格录入的值");
        });

    },
    getAlgList() {
      this.chuliMethods = [
        {
          key: "YCL_ZZSSF",
          label: "正整数算法",
        },
        {
          key: "YCL_JSPJZSF",
          label: "计算平均值算法_wait",
        },
        {
          key: "YCL_ZSSSF",
          label: "正实数算法",
        },
        {
          key: "YCL_PDSiDJSF",
          label: "判断四等级算法",
        },
        {
          key: "YCL_PDSDJSF",
          label: "判断三等级算法",
        },
        {
          key: "YCL_PDSFSF",
          label: "判断是否算法",
        },
        {
          key: "YCL_FFSSSF",
          label: "非负实数算法",
        },
        {
          key: "YCL_FFZSSF",
          label: "非负整数算法",
        },
      ];
      // getAlgsList().then((res) => {
      //   if (res.code == 200) {
      //     this.chuliMethods = res.data;
      //   }
      // });
    },
    tagClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.inputValue = "";
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    chuliClick(val) {
      this.inputValue = val.key;
      if (this.inputVisible) {
        this.handleInputConfirm();
      }
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (this.dynamicTags.indexOf(inputValue) !== -1) {
        this.$modal.msgError("不能选择重复的步骤");
        this.inputValue = "";
      } else {
        if (inputValue) {
          this.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = "";
      }
    },
   async commitStep() {
      if(this.dynamicTags.length== 0){
        this.$modal.msgSuccess("本地数据已更新，保存后生效");
      }
     setTimeout(() => {
       this.$set(this.settingRow, "dataPreprocessingAlg", this.dynamicTags.join(","));
      }, 100);
      this.$set(this.demoList.pretreatmentList, this.settingiIndex, this.settingRow)

      // this.$set(this.demoList.pretreatmentList[this.settingiIndex], "dataPreprocessingAlg",this.dynamicTags.join(","));
      // console.log(this.demoList.pretreatmentList,'123333')


      this.$modal.msgSuccess("本地数据已更新，保存后生效");
      // this.$refs.demoList.resetFields()
      setTimeout(() => {
        this.$refs.demoList.validate().then(valid => {
          if (valid) {// 表单验证通过，执行提交操作

          } else {// 表单验证不通过，不执行提交操作
            }});
      }, 100);

      this.methodsDialog = false;
    },

    getDict(dictType, key) {
      getDictList({
        pageNum: 1,
        pageSize: 20,
        dictType,
      }).then((res) => {
        if (res.code == 200) {
          this[key] = res.rows;
        }
      });
    },
    showlinkDialog() {
      this.linkDialog = true;
    },
    link() {
      this.linkDialog = false;
    },
    clearFiles(){
      this.$refs.upload.clearFiles();
    },
    clearFilesJSON(){
      this.$refs.uploadJSON.clearFiles();

    },
    uploadFileJSON(a, b, c) {
      var startTime =''
      var endTime =''
      if(this.linkForm.length != 0){
        startTime = this.linkForm[0]
        endTime = this.linkForm[1]
      }
      var formData = new FormData();
      formData.append("file", a.file);
      importJsonData(formData,{startTime:startTime,endTime:endTime}).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("上传成功");
          this.linkDialog = false;
          this.clearFilesJSON()
            res.data.forEach(item => {
              // originalValue
              // name
              const pretreatmentList = this.demoList.pretreatmentList.find(v => v.name == item.name)
              if (pretreatmentList) {
                pretreatmentList.originalValue = item.value.join(',')
              }
            })

        }else{
          this.clearFilesJSON()
          // return this.$modal.msgWarning("上传失败");
        }
        this.fileList = [];
      }).catch(err => {
        // 报错
        this.clearFilesJSON()
      });
    },
    uploadFile(a, b, c) {
      var formData = new FormData();
      formData.append("file", a.file);
      importTabel(formData).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("上传成功");
          this.searchP();
          this.clearFiles()
        }else{
          this.clearFiles()
          // return this.$modal.msgWarning("上传失败");
        }
        this.fileList = [];
      }).catch(err => {
      // 报错
        this.clearFiles()
    });
    },
    downTable(type) {
      if (
        !this.demoList.pretreatmentList.some((item) => {
          return  false
          // return item.normalizationAlgSet == ""||item.normalizationAlgSet == null;
        })
      ){
        tempEditzqz({
          id:this.commitModel.emid,
          taskId:this.commitModel.id,
          code:this.commitModel.code,
          name:this.commitModel.name,
          method:'',
          nodeList:this.demoList.pretreatmentList,
          // taskId: this.commitModel.id,
          // code: this.commitModel.code,
          // name: this.commitModel.name,
          // nodeList: this.pretreatmentList,
        }).then((res) => {
          if (res.code == 200) {
            exportXls({ emId: this.commitModel.emid, type: type.toString(),taskId: this.commitModel.id}).then((res) => {
              const url = window.URL.createObjectURL(
                new Blob([res], { type: "application/xlsx" })
              );
              const link = document.createElement("a");
              link.href = url;
              if(type=='1'){
                link.download = this.commitModel.name+"试验员打分表.xlsx";
              }else{
                link.download = this.commitModel.name+"专家打分表.xlsx";
              }
              link.click();
            });
          }
        });
      }else {
        this.$modal.msgWarning("请填写数据来源后重试");
      }


    },
    searchP() {
      this.pCurrPage = 1;
      this.getPretreatment();
    },
    async changePPage(val) {
      // await this.compareRows(this.rawData,this.demoList.pretreatmentList)
      if (this.deepCompareArrays(this.rawData,this.demoList.pretreatmentList)) {
        this.pCurrPage = val
        this.getPretreatment();
      } else {
        this.$confirm("是否保存表格内容?", "提示", {
          confirmButtonText: "保存",
          cancelButtonText: "取消保存",
          type: "warning",
        })
          .then(() => {
            this.pCurrPage = val
            this.zancun()
            this.getPretreatment();
          })
          .catch(() => {
            this.pCurrPage = val
            this.getPretreatment();
          });
      }
    },
    // 深度递归比较两个数组中的对象是否相同
    deepCompareArrays(arr1, arr2) {
      // 如果两个数组的长度不同，则它们肯定不相同
      if (arr1.length !== arr2.length) {
        return false;
      }

      // 对数组中的每个对象进行逐个比较
      for (let i = 0; i < arr1.length; i++) {
        const obj1 = arr1[i];
        const obj2 = arr2[i];

        // 如果其中一个对象为 null 或 undefined，则直接比较它们是否相等
        if (obj1 === null || obj1 === undefined || obj2 === null || obj2 === undefined) {
          if (obj1 !== obj2) {
            return false;
          }
        } else {
          // 否则，递归比较两个对象
          if (!this.deepCompareObjects(obj1, obj2)) {
            return false;
          }
        }
      }

      // 如果所有对象都相同，则返回 true
      return true;
    },

    // 深度递归比较两个对象的所有属性值是否相同
    deepCompareObjects(obj1, obj2) {
      // 如果两个值都是对象，则递归比较它们的属性值
      if (typeof obj1 === 'object' && typeof obj2 === 'object') {
        const keys1 = Object.keys(obj1);
        const keys2 = Object.keys(obj2);

        // 确保两个对象具有相同的属性数
        if (keys1.length !== keys2.length) {
          return false;
        }

        // 比较每个属性的值是否相同
        for (let key of keys1) {
          // 检查属性值是否为 null 或 undefined
          if (obj1[key] === null || obj1[key] === undefined || obj2[key] === null || obj2[key] === undefined) {
            // 如果其中一个属性值为 null 或 undefined，则直接比较它们是否相等
            if (obj1[key] !== obj2[key]) {
              return false;
            }
          } else {
            // 否则，递归比较对象的属性值
            if (!this.deepCompareObjects(obj1[key], obj2[key])) {
              return false;
            }
          }
        }

        // 如果所有属性的值都相同，则返回 true
        return true;
      } else {
        // 如果值不是对象，则直接比较它们
        return obj1 === obj2;
      }
    },

    changeModelPage() {
      this.getModel();
    },
    commitImport() {
      this.commitModel = this.currModel;
      importModel({ status: this.modelType, id: this.commitModel.id }).then((res) => {
        this.importDialog = false;
        this.$modal.msgSuccess("导入成功");
      });
      this.pCurrPage = 1;
      this.getPretreatment();
    },
    hasDoubleQuotes(str) {
      return str.indexOf('"') !== -1;
    },
    getPretreatment() {
      let params ={
        taskId:this.commitModel.id,
        emId:this.commitModel.emid,
        pageNo: this.pCurrPage,
        pageSize: 10,
        name: this.input4,
      }
      getTaskModelNodeList(params).then((res) => {
        if (res.code == 200) {
          this.demoList.pretreatmentList = res.data.records;
          this.pTotal = res.data.total;
          this.rawData=JSON.parse(JSON.stringify(res.data.records));

          this.demoList.pretreatmentList.forEach(item=>{
            if(this.hasDoubleQuotes(item.originalValue)){
              item.originalValue = item.originalValue.replace(/^\"|\"$/g, '');
              // item.originalValue = JSON.parse(item.originalValue)
            }
          })

        }
      });
      // getPretreatmentList({
      //   code: this.modelType,
      //   pageNo: this.pCurrPage,
      //   pageSize: 10,
      //   name: this.input4,
      // }).then((res) => {
      //   console.log(res);
      //   if (res.code == 200) {
      //     res.data.records.map((e) => {
      //       if (!e.dataPreprocessingAlg) {
      //         e.dataPreprocessingAlg = "";
      //       }
      //       return e;
      //     });
      //     this.pretreatmentList = res.data.records;
      //     this.pTotal = res.data.total;
      //   }
      // });
    },
    calc() {
      if (
        !this.demoList.pretreatmentList.some((item) => {
          return false
          // return item.normalizationAlgSet == ""||item.normalizationAlgSet == null;
        })
      ) {
        this.$refs.demoList.validate().then(valid => {
          if (valid) {// 表单验证通过，执行提交操作
            let nodeList = JSON.parse(JSON.stringify(this.demoList.pretreatmentList));
            nodeList.forEach(item=>{
              if(this.hasChinese(item.originalValue)){
                item.originalValue = '"' + item.originalValue + '"'
              }
            })
            tempEditzqz({
              id:this.commitModel.emid,
              taskId:this.commitModel.id,
              code:this.commitModel.code,
              name:this.commitModel.name,
              method:'',
              nodeList:nodeList,
              // taskId: this.commitModel.id,
              // code: this.commitModel.code,
              // name: this.commitModel.name,
              // nodeList: this.pretreatmentList,
            }).then((res) => {
              if (res.code == 200) {
                computeValue({emId:this.commitModel.emid, taskId:this.commitModel.id,}).then((res) => {
                  this.$modal.msgSuccess("计算完成");
                  this.jsRes=false
                  selectTreeByCode({emId:this.commitModel.emid, taskId:this.commitModel.id,}).then((res) => {
                    if (res.code == 200) {
                      const data = res.data
                      this.formatTree(data);
                      this.g6Tree = data;
                      // console.log(this.g6Tree,'g6数据')
                    }
                  });
                });
              }
            });
          } else {// 表单验证不通过，不执行提交操作
          }}).catch(() => {
          this.$modal.msgWarning("请检查表格录入的值");
        });

        // tempEdit({
        //     code: this.commitModel.code,
        //     name: this.commitModel.name,
        //     nodeList: this.pretreatmentList,
        // }).then((res) => {
        //   if (res.code == 200) {
        //
        //   }
        // });
      } else {
        this.$modal.msgWarning("请填写系统标准数据");
      }
    },
    view() {},
    deleteRow(row,index) {
      this.settingRow = row;
      this.dynamicTags=[]
      this.$set(this.demoList.pretreatmentList, index, this.settingRow )
      this.settingiIndex = index;
      this.methodsDialog = true;
    },
    rowClick(val) {
      this.currModelId = val.id;
      this.currModel = val;
    },
    onSubmit() {
      this.modelCurrPage = 1;
      this.getModel();
    },
    importByPing() {
      this.modelType = 1;
      this.modelCurrPage = 1;
      this.importDialogTitle = PINGTITLE;
      this.importType = PING;
      this.getModel();
    },
    importByCao() {
      this.modelType = 2;
      this.modelCurrPage = 1;
      this.importDialogTitle = CAOTITLE;
      this.importType = CAO;
      this.getModel();
    },
    getModel() {
      const params = {
        createTime: this.formInline.createTime,
        type: this.formInline.type,
        modelName: this.formInline.modelName,
        status: this.modelType,
        pageNo: this.modelCurrPage,
        pageSize: 10,
      };
      this.importDialog = true;
      getModelList(params).then((res) => {
        if (res.code == 200) {
          this.modelList = res.data.records;
          this.modelTotle = res.data.total;
        }
      });
    },
    handleSelectionChange() {},
  },
};
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 10px;
  ::v-deep .el-date-editor--daterange.el-input__inner {
    width: 250px;
  }
  ::v-deep .el-button span {
    display: flex;
    align-items: center;
    img {
      display: block;
      margin-right: 5px;
    }
  }
  .flexAlign {
    display: flex;
    align-items: center;
    img {
      display: block;
      margin-right: 5px;
    }
    span {
      display: flex;
      align-items: center;
    }
  }
  .lineBlue{
    width: 2px;margin-left: 10px;margin-right: 10px;
    height: 20px;
    background: #3670F5;
    opacity: 0.6;
    border-radius: 1px;
  }
  .calcMain {
    overflow-y: auto;
    background-color: #fff;
    box-shadow: 0 0 10px 10px #ccc;
    background: linear-gradient(180deg, rgba(255, 255, 255, 0.8), #ffffff);
    box-shadow: 0px 4px 10px 0px rgba(0, 34, 64, 0.05);
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);
    border-radius: 5px;
    height: 100%;
    width: 100%;
    .topBtn {
      height: 50px;
      padding: 10px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #e4e8f1;
      .line {
        width: 1px;
        height: 30px;
        margin: 0 20px;
        background: #e4e8f1;
        border-radius: 1px;
      }
      .pageTitle {
        font-size: 18px;
        font-family: Alibaba PuHuiTi;
        font-weight: 600;
        color: #3771f5;
        letter-spacing: 2px;

        line-height: 30px;
      }
    .huiTitle{
      margin-left: 10px;
      letter-spacing: 1px;
      font-size: 18px;
      font-family: Alibaba PuHuiTi;
      font-weight: 500;
      color: #878C98;
      line-height: 30px;
    }
      .pageTitle1 {
        font-size: 18px;
        font-family: Alibaba PuHuiTi;
        font-weight: 500;
        color: #333;
        line-height: 30px;
      }
      .qing {
        font-size: 14px;
        font-family: Alibaba PuHuiTi;
        font-weight: 400;
        color: #878c98;
        line-height: 30px;
      }
      .xinjian {
        font-size: 18px;
        font-family: Alibaba PuHuiTi;
        font-weight: 500;
        color: #3771f5;
        line-height: 30px;
      }
      .uploadDemo {
        margin-left: 10px;
      }
    }
    .bottomMain {
      padding: 10px;
      box-sizing: border-box;
      .title1,
      .title2 {
        font-size: 18px;
        font-family: Alibaba PuHuiTi;
        font-weight: 400;
        color: #393b3c;
        line-height: 38px;
      }
      .addForm {
        width: 500px;
        margin: 50px auto;
      }
      .tableContainer {
        width: 100%;
        padding: 0 10px 10px;
        box-sizing: border-box;
        background: #ffffff;
        border: 1px solid #91b2cc;
        border-radius: 4px;
        .searchInput {
          margin-right: 10px;
        }
        .myTabel {
          margin: 0 0 10px;
          width: 100%;
          .tableLineInput {
            width: 100px;
            /*margin-top: 20px;*/
          }
        }
      }
      .graph {
        width: 100%;
        height: 400px;
        border: 1px solid #91b2cc;
        border-radius: 4px;
      }
      .bottomBtn {
        width: 100%;
        margin-top: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
  .timeItem {
    height: 30px;
    width: 30px;
    position: absolute;
    left: -11px;
    top: 0;
    cursor: pointer;
  }
  .hisInfoItem {
    line-height: 30px;
    color: #5f6678;
    & > div:nth-child(1) {
      padding: 8px;
      line-height: 22px;
      box-sizing: border-box;
      width: 100%;
      background-color: #f0f4fc;
      border-radius: 4px;
      font-size: 18px;
      font-weight: 700;
    }
  }
}
</style>
